package com.xzk.controller.wx;

import com.xzk.bean.*;
import com.xzk.exception.DuplicateIdCardException;
import com.xzk.exception.DuplicatePhoneException;
import com.xzk.service.CourierService;
import com.xzk.service.UserService;
import com.xzk.util.DateFormatUtil;
import com.xzk.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @ClassName UserController
 * @Description 微信用户控制
 * @Author 0715-YuHao
 * @Date 2020/9/15 16:14
 * @Version 1.0
 */
@Controller("wxUserController")
@RequestMapping("/wx")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CourierService courierService;

    @RequestMapping("/loginSms.do")
    public @ResponseBody Message sendSms(HttpServletRequest request) {
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
//        String code = RandomCodeUtil.getCode();
//        boolean sms = SMSUtil.loginSMS(userPhone, code);
        String code = "111111";
        boolean sms = true;
        if (sms) {
            message.setStatus(0);
            message.setContent("验证码已发送，请查收！");
        }else {
            message.setStatus(-1);
            message.setContent("验证码发送失败，请检查手机号或稍后再试！");
        }
        UserUtil.setLoginSms(request.getSession(), userPhone, code);
        return message;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/login.do")
    public @ResponseBody Message login(HttpServletRequest request, HttpServletResponse response) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();
        Map<String, String> loginMap = (Map<String, String>) application.getAttribute("loginMap");
        if (loginMap == null) {
            loginMap = new HashMap<>();
        }
        Message message = new Message();
        String userPhone = request.getParameter("userPhone");
        String username = null;
        String userCode = request.getParameter("code");
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
        if (sysCode == null) {
            message.setStatus(-1);
            message.setContent("你输入的手机号码未获取短信");
        }else {
            if (sysCode.equals(userCode)) {
                String timeStamp = String.valueOf(new Date().getTime());
                Courier courier = courierService.findByPhone(userPhone);
                if (courier != null) {
                    message.setStatus(0);
                    UserUtil.setUserInfo(session, 0);
                    message.setContent("登录成功！");
                    courierService.updateLoginTime(userPhone);
                    username = courier.getName();
                    if (username != null) {
                        session.setAttribute("username", username);
                    }
                    session.setAttribute("userPhone", userPhone);
                    loginMap.put("wxCourier" + userPhone, timeStamp);
                    application.setAttribute("loginMap", loginMap);
                    Cookie cookie = new Cookie("wxCourier" + userPhone, timeStamp);
                    cookie.setMaxAge(60 * 60 * 24 * 7);
                    response.addCookie(cookie);
                }else {
                    User user = userService.findByPhone(userPhone);
                    if (user != null) {
                        message.setStatus(0);
                        UserUtil.setUserInfo(session, 1);
                        message.setContent("登录成功！");
                        userService.updateLoginTime(userPhone);
                        username = user.getNickName();
                        if (username != null) {
                            session.setAttribute("username", username);
                        }
                        session.setAttribute("userPhone", userPhone);
                        loginMap.put("wxUser" + userPhone, timeStamp);
                        application.setAttribute("loginMap", loginMap);
                        Cookie cookie = new Cookie("wxUser" + userPhone, timeStamp);
                        cookie.setMaxAge(60 * 60 * 24 * 7);
                        response.addCookie(cookie);
                    }else {
                        try {
                            boolean flag = userService.signUp(userPhone);
                            if (flag) {
                                message.setStatus(0);
                                message.setContent("注册成功！");
                                UserUtil.setUserInfo(session, 1);
                                userService.updateLoginTime(userPhone);
                                session.setAttribute("userPhone", userPhone);
                                loginMap.put("wxUser" + userPhone, timeStamp);
                                application.setAttribute("loginMap", loginMap);
                                Cookie cookie = new Cookie("wxUser" + userPhone, timeStamp);
                                cookie.setMaxAge(60 * 60 * 24 * 7);
                                response.addCookie(cookie);
                            }else {
                                message.setStatus(-1);
                                message.setContent("注册失败！");
                            }
                        } catch (DuplicatePhoneException e) {
                            message.setStatus(-1);
                            message.setContent("手机号已注册，请直接登录！");
                        }
                    }
                }
            }else {
                message.setStatus(-1);
                message.setContent("验证码不一致,请检查输入！");
            }
        }
        return message;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/login2.do")
    public @ResponseBody Message login2(HttpServletRequest request) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();
        Map<String, String> loginMap = (Map<String, String>) application.getAttribute("loginMap");
        if (loginMap == null) {
            return new Message(-1, "未登录！");
        }
        String userPhone = null;
        Message msg = new Message();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("wxCourier".equals(cookie.getName().substring(0,9))) {
                userPhone = cookie.getName().substring(9);
                if (loginMap.get(cookie.getName()).equals(cookie.getValue())) {
                    session.setAttribute("userPhone", userPhone);
                    UserUtil.setUserInfo(session, 0);
                    msg.setStatus(0);
                }else {
                    msg.setStatus(-1);
                }
            }else if ("wxUser".equals(cookie.getName().substring(0,6))) {
                userPhone = cookie.getName().substring(6);
                if (loginMap.get(cookie.getName()).equals(cookie.getValue())) {
                    session.setAttribute("userPhone", userPhone);
                    UserUtil.setUserInfo(session, 1);
                    msg.setStatus(0);
                } else {
                    msg.setStatus(-1);
                }
            }else {
                msg.setStatus(-1);
            }
        }
        return msg;
    }

    @RequestMapping("/logout.do")
    public @ResponseBody Message logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        Map<String, String> loginMap = (Map<String, String>) application.getAttribute("loginMap");
        String userPhone = UserUtil.getUserPhone(session);
        if (userPhone != null) {
            int userInfo = UserUtil.getUserInfo(session);
            session.invalidate();
            Cookie cookie = null;
            if (userInfo == 0) {
                loginMap.remove("wxCourier" + userPhone);
                cookie = new Cookie("wxCourier" + userPhone, "cancel");
            }else if (userInfo == 1){
                loginMap.remove("wxUser" + userPhone);
                cookie = new Cookie("wxUser" + userPhone, "cancel");
            }
            application.setAttribute("loginMap", loginMap);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        return new Message(0);
    }

    @RequestMapping("/userInfo.do")
    public @ResponseBody Message userInfo(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userInfo = UserUtil.getUserInfo(session);
        String userPhone = UserUtil.getUserPhone(session);
        String username = UserUtil.getUserName(session);
        Message message = new Message();
        Map<String, String> data = new HashMap<>();
        message.setStatus(userInfo);
        if (username != null) {
            message.setContent("欢迎" + username);
            data.put("username", username);
        }else {
            message.setContent("欢迎" + userPhone);
        }
        data.put("userPhone", userPhone);
        message.setData(data);
        return message;
    }

    @RequestMapping("/userStatus.do")
    public @ResponseBody Message userStatus(HttpServletRequest request) {
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
        User user = userService.findByPhone(userPhone);
        message.setStatus(user.getStatus());
        return message;
    }

    @RequestMapping("/getUserInfo.do")
    public @ResponseBody Message getUserInfo(HttpServletRequest request) {
        int type = Integer.parseInt(request.getParameter("type"));
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
        String showPhone = userPhone.substring(0, 3) + "****" + userPhone.substring(7, 11);
        if (type == 0) {
            Courier courier = courierService.findByPhone(userPhone);
            String idCard = courier.getIdCard();
            String showIdCard = idCard.substring(0, 6) + "*******" + idCard.substring(13, 18);
            BootStrapTableCourier showCourier = new BootStrapTableCourier(
                    courier.getId(),
                    courier.getName(),
                    showPhone,
                    showIdCard,
                    "******",
                    courier.getNumberDispatch(),
                    "已激活",
                    DateFormatUtil.formatDate(courier.getSignUpTime()),
                    DateFormatUtil.formatDate(courier.getLoginTime())
            );
            message.setStatus(0);
            message.setData(showCourier);
        }else {
            User user = userService.findByPhone(userPhone);
            String idCard = user.getIdCard();
            String showIdCard = idCard.substring(0, 6) + "*******" + idCard.substring(12, 18);
            BootStrapTableUser showUser = new BootStrapTableUser(
                    user.getId(),
                    user.getNickName(),
                    showPhone,
                    showIdCard,
                    "******",
                    "已激活",
                    DateFormatUtil.formatDate(user.getSignUpTime()),
                    DateFormatUtil.formatDate(user.getLoginTime())
            );
            message.setStatus(0);
            message.setData(showUser);
        }
        return message;
    }

    @RequestMapping("/getUserInfo2.do")
    public @ResponseBody Message getUserInfo2(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userPhone = UserUtil.getUserPhone(session);
        Message message = new Message();
        if (UserUtil.getUserInfo(session) == 0) {
            Courier courier = courierService.findByPhone(userPhone);
            message.setStatus(0);
            message.setData(courier);
        }else {
            User user = userService.findByPhone(userPhone);
            message.setStatus(1);
            message.setData(user);
        }
        return message;
    }


    @RequestMapping("/verified.do")
    public @ResponseBody Message verified(HttpServletRequest request) {
        String nickName = request.getParameter("nickName");
        String phone = request.getParameter("phone");
        String idCard = request.getParameter("idCard");
        String password = request.getParameter("password");
        Message message = new Message();
        try {
            boolean insert = userService.updateByPhone(phone, new User(nickName, idCard, password));
            if (insert) {
                message.setStatus(0);
                message.setContent("注册成功");
            }else {
                message.setStatus(-1);
                message.setContent("注册失败");
            }
        } catch (DuplicateIdCardException e) {
            message.setStatus(-1);
            message.setContent("身份证已被注册！");
        }
        return message;
    }

    @RequestMapping("/userUpdate.do")
    public @ResponseBody Message update(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String name = request.getParameter("name");
        session.setAttribute("username", name);
        String password = request.getParameter("password");
        String userPhone = request.getParameter("userPhone");
        Message message = new Message();
        String userCode = request.getParameter("code");
        String sysCode = UserUtil.getLoginSms(session, userPhone);
        int type = UserUtil.getUserInfo(session);
        if (sysCode == null) {
            message.setStatus(-1);
            message.setContent("你输入的手机号码未获取短信");
        }else{
            if (sysCode.equals(userCode)) {
                if (type == 0) {
                    courierService.updateByWx(userPhone, new Courier(name, password));
                }else {
                    userService.updateByWx(userPhone, new User(name, password));
                }
                session.removeAttribute(userPhone);
                message.setStatus(0);
                message.setContent("修改成功");
            }else {
                message.setStatus(-1);
                message.setContent("验证码不一致,请检查输入！");
            }
        }
        return message;
    }
}
